#include <iostream>
#include "Thread.hpp"
#include <unistd.h>
#include <vector>

using namespace ThreadMoudle;

const int N = 20;

int ticketnum = 10000;




// 模拟库

// ThreadMoudle::Mutex gmtx;

ThreadMoudle::LockGuard glockg;

class ThreadData
{
public:
    std::string _name;
    // pthread_mutex_t *lock_ptr;
};



void Ticket(ThreadData data)
{
    while(true)
    {
        // gmtx.Lock();
        glockg.Lock();
        if(ticketnum > 0)
        {
            usleep(1000);
            
            std::cout<<"i am "<<data._name<<",i got ticket="<<ticketnum<<std::endl;
            ticketnum--;

            glockg.Unlock();
            // gmtx.Unlock();

            usleep(1000);
        }
        else 
        {
            glockg.Unlock();
            // gmtx.Unlock();
            break;
        }
            
    }
}


int main()
{
    std::vector<Thread<ThreadData>> threads;
    

    for(int i= 1; i<= N; ++i)
    {
        threads.emplace_back(Thread<ThreadData>(Ticket,{"thread-"+std::to_string(i)}));
    }
    for(auto& t : threads)
    t.Start();


    sleep(5);
    
    for(auto& t : threads)
    {
        std::cout<<"join "<<t.Name()<<" = "<<t.Join()<<std::endl;
    }

    return 0;
}


